import java.io.IOException;

import server.ServerConnection;

/**
 * The main method for the server.
 * 
 * @author ic08jh7
 * 
 */
public class ServerMain {

	/**
	 * Establishes a connection with a mySQL database via JDBC and waits for a
	 * client to connect. The server will use port 9999.
	 * 
	 * @param args
	 *            [0] The user name to the database to be used.
	 * @param args
	 *            [1] The password to the database to be used.
	 * @param args
	 *            [2] The url to the database to be used.
	 */
	public static void main(String[] args) {

		String user, password, url;
		user = args[0];
		password = args[1];
		url = args[2];
		ServerConnection s = new ServerConnection(user, password, url, 9999);
		System.out.println(s.waitForConnection());

		while (s.isConnected()) {
			if (!s.isClosed()) {
				String in = s.getInput();
				if (in == null) {
					s.close();
					continue;
				} else {

					try {
						s.sendToClient(in);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				System.out.println(in);
				System.out.flush();
			} else {
				s = new ServerConnection(user, password, url, 9999);
				System.out.println("Connection is closed!");
				s.waitForConnection();

			}
		}
	}
}
